﻿using AntDesign;
using AntDesign.TableModels;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Web;
using SE.PO.CInterface.DBProtocols.Devices;
using SE.PO.CInterface.Po.Equips;
using SE.PO.CInterface.Po.Variables;

namespace SE.PO.CInterface.Web.Pages.DB.Components;

public partial class SelectVariables
{
    #region query

    [Parameter] public SelectSignalCoding? SelectSignalCoding { get; set; }
    [Parameter] public SelectDevices? SelectDevices { get; set; }

    List<VariableDto> _source = new();

    private string? TagName { get; set; }

    public IEnumerable<VariableDto>? SelectedVariablesDto;

    ITable? _table;

    int _pageIndex = 1;
    int _pageSize = 10000;
    int _total;
    private bool _loadingData=true;

    protected override async Task OnInitializedAsync()
    {
        await GetSourceAsync(_pageIndex, _pageSize);
    }

    private async Task OnFinish(EditContext editContext)
    {
        await GetSourceAsync(_pageIndex, _pageSize);
    }

    public async Task Reset()
    {
        TagName = string.Empty;
        await GetSourceAsync(_pageIndex, _pageSize);
    }

    public async Task Search()
    {
        await GetSourceAsync(_pageIndex, _pageSize);
    }

    public async Task GetSourceAsync(int pageIndex = 0, int pageSize = int.MaxValue)
    {
        try
        {
            _loadingData = true;
            var selectedEquips = from d in (SelectDevices?.SelectedDevices ?? new List<DeviceDto>()) select d.Equipment;
            var result = await Client.Get(TagName, SelectSignalCoding?.SelectedMonitorInfoCode,
                selectedEquips.ToList());
            if (result != null)
            {
                _source = result.Items.ToList();
                SelectedVariablesDto = _source;
                _total = _source.Count;
                _pageSize = _source.Count;
            }
            _loadingData = false;
            StateHasChanged();
            _loadingData = false;
        }
        catch (System.Exception ex)
        {
            _ = Notice.Error(new()
            {
                Duration = 100,
                Message = "异常",
                Description = ex.Message
            });
        }
        finally
        {
            _loadingData = false;
        }
    }

    #endregion
}